$(document).ready(function(e) {
	window.conWidth = $('#showImgCon').width();
	window.conHeight = $('#showImgCon').height();
	window.cutWidth = window.conWidth * 0.3;
	window.cutHeight = window.conHeight * 0.3;
	window.oldImgObj = {};

	initEvents();
	initLayout();

	// window.selectImgId = '1608240105';
	// showUploadPic('/pic/show/1608240105');
});
function initLayout() {
	$('#imgTitleCon').css({ width : window.conWidth - 14, height : window.conHeight - 14 });
	var tLeft = (window.conWidth - $('#imgTitle').outerWidth()) / 2;
	var tTop = (window.conHeight - $('#imgTitle').outerHeight()) / 2;
	$('#imgTitle').css({ top : tTop, left : tLeft });

	var lLeft = (window.conWidth - $('#loadingCon').outerWidth()) / 2;
	var lTop = (window.conHeight - $('#loadingCon').outerHeight()) / 2;
	$('#loadingCon').css({ top : lTop, left : lLeft }).hide();

}

function initEvents() {
	$(window).bind('resize', function() {
	});

	$(document).bind("dragover", function(e) {
		imgTitle.style.borderColor = 'red';
		e.stopPropagation();
		e.preventDefault();
	});
	$(document).bind("dragleave", function(e) {
		imgTitle.style.borderColor = 'silver';
		e.stopPropagation();
		e.preventDefault();
	});
	$(document).bind("drop", function(e) {
		imgTitle.style.borderColor = 'silver';
		e.stopPropagation();
		e.preventDefault();
	});

	$('#imgTitleCon').bind("dragleave", function(e) {
		imgTitle.style.backgroundColor = 'transparent';
		e.stopPropagation();
		e.preventDefault();
	});
	$('#imgTitleCon').bind("dragover", function(e) {
		imgTitle.style.backgroundColor = '#CA7332';
		e.stopPropagation();
		e.preventDefault();
	});

	$('#imgTitle').bind("drop", function(e) {
		$('#imgTitleCon').hide();
		$('#imgLoading').show();

		imgTitle.style.backgroundColor = 'transparent';
		// handleFiles(e.dataTransfer.files);
		// alert(e.dataTransfer.files)
		var file = e.dataTransfer.files[0];
		var reader = new FileReader();
		reader.readAsDataURL(file);

		var xhr = new XMLHttpRequest();
		var url = '/pic/upload';
		var boundary = '-----------------------' + new Date().getTime();
		var name = 'image';
		var crlf = '\r\n';
		var dashes = "--";

		xhr.onreadystatechange = function(e) {
			// alert(e+':'+xhr.responseText);
			if (xhr.readyState == 4 && xhr.status == 200) {
				var urlStr = xhr.responseText;
				var re = new RegExp('[\d]+', 'ig');
				var result = urlStr.match(re);
				var id = result != null && result.length > 0 ? result[0] : '';
				// alert(url);
				uploadAfter(id);
			}
		};
		xhr.open("POST", url, true);
		if (file.getAsBinary) {
			var data = dashes + boundary + crlf + "Content-Disposition: form-data;" + "name=\"" + name + "\";" + "filename=\"" + unescape(encodeURIComponent(file.name)) + "\"" + crlf + "Content-Type: application/octet-stream" + crlf + crlf + file.getAsBinary() + crlf + dashes + boundary + dashes;
			xhr.setRequestHeader("Content-Type", "multipart/form-data;boundary=" + boundary);
			xhr.sendAsBinary(data);
		} else if (window.FormData) {
			var formData = new FormData();
			formData.append(name, file);
			xhr.send(formData);
		}

		e.stopPropagation();
		e.preventDefault();
	}, false);

	$('.coolBtn').css('opacity', '0.5').mouseenter(function() {
		$(this).addClass('coolBtn_over');
	}).mouseleave(function() {
		$(this).removeClass('coolBtn_over');
	});

	$('#selectFileBtn').click(function() {
		$('#file').click();
	});

	$('#file').change(function(e) {
		$('#imgTitleCon').hide();
		$('#imgLoading').show();

		window.isUploadSubmit = 1;
		$('#profile_edit_personal_pic_form').submit();
	});
	// $('#profile_edit_personal_pic_form').submit(function(e) {
	// var isSubmit = window.isUploadSubmit == 1;
	// window.isUploadSubmit = 0;
	// return isSubmit;
	// });

	$('.cover_image_btn').mouseenter(function() {
		$(this).addClass('cover_image_btn_over');
	}).mouseleave(function() {
		$(this).removeClass('cover_image_btn_over');
	});

	$('#moveImageTitle').mouseenter(function() {
		$(this).css('opacity', 0.85);
	}).mouseleave(function() {
		$(this).css('opacity', 0.5);
	});

	$('#cover_image').mouseenter(function(e) {
		if (!$('#saveBtn').is(':visible')) {
			$('#coverImageBtn').show();
		}
	}).mouseleave(function(e) {
		if (!$('#uploadImgCon').is(':visible')) {
			$('#coverImageBtn').hide();
		}
	});
	$('#coverImageBtn').click(function(e) {
		$('#uploadImgCon').show('fast', function() {
			$("html,body").animate({ 'scrollTop' : $('#coverImageBtn').offset().top - 32 }, 'fast');
		});
	});
	$('#cancelUploadBtn').click(function(e) {
		$('#imgCon').empty().hide();
		$('#imgConCut').hide();
		$('#uploadPicLoading').hide();
		$('#imgTitleCon').show();
		$('#saveUpdateBtn').attr('disabled', true).removeClass('button_over');
		$('#uploadImgCon').hide('fast');
		$('#zoomText').text('');
	});

	$('#profile_edit_personal_pic_form').submit(function(e) {
		// window.oldImgObj.bi = 1.00;
		// showUploadPic('./images/ttt.jpg');
		// return false;

		var isSubmit = window.isUploadSubmit == 1;
		window.isUploadSubmit = 0;
		return isSubmit;
	});
	$('#imgCon').mousedown(function(e) {
		var pcstr = $('#imgConCut').css('backgroundPosition');
		if (pcstr != null) {
			var pc = pcstr.replace(/px/g, '').split(' ');
			var pX = $('#imgCon').position().left, pY = $('#imgCon').position().top;
			var pcX = parseFloat(pc[0]), pcY = parseFloat(pc[1]);
			$(document).data('movePicData', { type : '#imgCon', x : e.clientX, y : e.clientY, pX : pX, pY : pY, pcX : pcX, pcY : pcY });
		}
		return false;
	});
	$('#imgConCut').mousedown(function(e) {
		// var pstr = $('#imgCon').css('backgroundPosition');
		var pcstr = $('#imgConCut').css('backgroundPosition');
		if (pcstr != null) {
			var pc = pcstr.replace(/px/g, '').split(' ');
			var pX = $('#imgCon').position().left, pY = $('#imgCon').position().top;
			var pcX = parseFloat(pc[0]), pcY = parseFloat(pc[1]);
			var cTop = $('#imgConCut').position().top, cLeft = $('#imgConCut').position().left;
			$(document).data('movePicData', { type : 'imgConCut', x : e.clientX, y : e.clientY, pX : pX, pY : pY, pcX : pcX, pcY : pcY, cTop : cTop, cLeft : cLeft });
		}

		return false;
	});
	$(document).mouseup(function(e) {
		$(document).data('movePicData', null);
		return false;
	}).mousemove(function(e) {
		var moveObj = $(document).data('movePicData');
		if (moveObj != null) {
			var moveX = e.clientX - moveObj.x, moveY = e.clientY - moveObj.y;

			if (moveObj.type == 'imgConCut') {
				var cutLeft = moveObj.cLeft + moveX, cutTop = moveObj.cTop + moveY;
				var width = $('#showImgCon').innerWidth(), height = $('#showImgCon').innerHeight();
				var cWidth = $('#imgConCut').outerWidth(), cHeight = $('#imgConCut').outerHeight();
				var imgMWidth = $('#imgCon').innerWidth() + $('#imgCon').position().left;
				var imgMHeight = $('#imgCon').innerHeight() + $('#imgCon').position().top;
				width = width > imgMWidth ? imgMWidth : width;
				height = height > imgMHeight ? imgMHeight : height;
				var maxWidth = width - cWidth, maxHeight = height - cHeight;
				var minWIdth = $('#imgCon').position().left > 0 ? $('#imgCon').position().left : 0;
				var minHeight = $('#imgCon').position().top > 0 ? $('#imgCon').position().top : 0;
				cutLeft = cutLeft < minWIdth ? minWIdth : cutLeft;
				cutLeft = cutLeft > maxWidth ? maxWidth : cutLeft;
				cutTop = cutTop < minHeight ? minHeight : cutTop;
				cutTop = cutTop > maxHeight ? maxHeight : cutTop;
				// 修正
				moveX = cutLeft - moveObj.cLeft;
				moveY = cutTop - moveObj.cTop;

				pcStr = (moveObj.pcX - moveX) + 'px ' + (moveObj.pcY - moveY) + 'px';
				$('#imgConCut').css({ left : cutLeft, top : cutTop });
			} else {
				var left = moveObj.pX + moveX, top = moveObj.pY + moveY;
				left = left > $('#imgConCut').position().left ? $('#imgConCut').position().left : left;
				top = top > $('#imgConCut').position().top ? $('#imgConCut').position().top : top;
				var minWidth = $('#imgConCut').position().left + $('#imgConCut').outerWidth() - $('#imgCon').outerWidth();
				var minHeight = $('#imgConCut').position().top + $('#imgConCut').outerHeight() - $('#imgCon').outerHeight();
				left = left < minWidth ? minWidth : left;
				top = top < minHeight ? minHeight : top;
				$('#imgCon').css({ 'left' : left, 'top' : top });
			}
			// var minLeft = $('#imgConCut').position().left + $('#imgConCut').outerWidth() - $('#imgCon').outerWidth();
			// var minTop = $('#imgConCut').position().top + $('#imgConCut').outerHeight() - $('#imgCon').outerHeight();
			var cutMovePX = $('#imgCon').position().left - $('#imgConCut').position().left, cutMovePY = $('#imgCon').position().top - $('#imgConCut').position().top;
			cutMovePX = cutMovePX > 0 ? 0 : cutMovePX;
			cutMovePY = cutMovePY > 0 ? 0 : cutMovePY;
			// cutMovePX = cutMovePX < minLeft ? minLeft : cutMovePX;
			// cutMovePY = cutMovePY < minTop ? minTop : cutMovePY;

			// var pcStr = cutMovePX + 'px ' + cutMovePY + 'px';
			$('#imgConCutImg').css({ left : cutMovePX, top : cutMovePY });
		}
		return false;
	});
	$('#saveUpdateBtn').mousedown(function(e) {
		var bi = window.conWidth / window.cutWidth;
		var width = window.cutWidth * bi;
		var height = window.cutHeight * bi;
		var x = $('#imgConCut').position().left - $('#imgCon').position().left;
		var y = $('#imgConCut').position().top - $('#imgCon').position().top;
		x = x * bi;
		y = y * bi;
		var scaledWidth = $('#imgCon').width() * bi;
		var scaledHeight = $('#imgCon').height() * bi;
		scaledWidth = scaledWidth < (x + width) ? (x + width) : scaledWidth;
		scaledHeight = scaledHeight < (y + height) ? (y + height) : scaledHeight;

		var params = [ 'width=' + parseInt(width) ];
		params.push('height=' + parseInt(height));
		params.push('x=' + parseInt(x));
		params.push('y=' + parseInt(y));
		// if (window.oldImgObj.bi != 1.00) {
		params.push('scaledWidth=' + parseInt(scaledWidth));
		params.push('scaledHeight=' + parseInt(scaledHeight));
		// }
		params.push('_method=put');
		$('#loadingCon').show();
		$.ajax({ url : '/profile/api/rest/user-cover/' + userId + '/crop.json', type : "post", data : params.join('&'), crossDomain : false, success : function(data) {
			var s = eval(data);
			if (s.success) {
				$('#loadingCon').hide();
				$('#cover_image').css('backgroundImage', 'url("' + s.url + '")');
				$('#cancelUploadBtn').click();
			}
		}, complete : function(msg) {
		} });
		return false;
	});
	$('#rotationBtn').click(function(e) {
		if ($('#imgTitle').is(':visible')) {
			alert('请先选择图片!');
			return;
		}
		if ($('#rotationBtn').data('isExe') == true) {
			return;
		}
		var url = '/pic/rotate';
		var r = 90;

		$('#rotationBtn').data('isExe', true);
		var params = [ 'degree=' + r, 'imgId=' + window.selectImgId ];
		$('#rotationBtn').text('旋转...');
		$('#loadingCon').show();
		$.ajax({ url : url, type : "POST", dataType : 'json', data : params.join('&'), success : function(re) {
			uploadAfter(re.imgId);
			$('#rotationBtn').text('旋转');
		}, complete : function(msg) {
			$('#rotationBtn').data('isExe', false);
			$('#loadingCon').fadeOut();
		} });
	});
	$('#zoomBtn').click(function(e) {
		if ($('#imgTitle').is(':visible')) {
			alert('请先选择图片!');
			return;
		}
		var width = $('#imgCon').width();
		width = width * 1.05;
		moozImg(width);
		if (window.event) {
			window.event.cancelBubble = true;// 否则，我们需要使用IE的方式来取消事件冒泡
		} else {
			// 因此它支持W3C的stopPropagation()方法
			e.stopPropagation();
		}
		return false;
	});
	$('#narrowBtn').click(function(e) {
		if ($('#imgTitle').is(':visible')) {
			alert('请先选择图片!');
			return;
		}
		var width = $('#imgCon').width();
		width = width * 0.95;
		moozImg(width);
		if (window.event) {
			window.event.cancelBubble = true;// 否则，我们需要使用IE的方式来取消事件冒泡
		} else {
			// 因此它支持W3C的stopPropagation()方法
			e.preventDefault();
			e.stopPropagation();
		}
		return false;
	});
}
function uploadAfter(imgId) {
	window.selectImgId = imgId;
	showUploadPic('/pic/show/' + imgId);
}
function showUploadPic(url) {
	loadImg(url, function(img) {

		window.oldImgObj.url = img.src;
		window.oldImgObj.width = img.width;
		window.oldImgObj.height = img.height;
		window.oldImgObj.bi = window.oldImgObj.bi ? window.oldImgObj.bi : 1;
		// var positionStr = left + 'px ' + top + 'px';

		$('#loadingCon').hide();
		$('#imgTitleCon').hide();
		$('#imgCon').attr('src', img.src).css({ 'cursor' : 'move', 'opacity' : 0.5 }).show();
		// $('#imgCon').css({ top : top, left : left });
		$('#imgConCut').css({ 'cursor' : 'move', width : window.cutWidth, height : window.cutHeight }).show();
		$('#imgConCutImg').attr('src', img.src).css({ 'cursor' : 'move' });

		var imgWidth = window.oldImgObj.bi * img.width;
		if (imgWidth > window.conWidth) {
			imgWidth = window.conWidth;
		}
		if (imgWidth < window.cutWidth) {
			imgWidth = window.cutWidth + 10;
		}
		window.oldImgObj.bi = imgWidth / window.oldImgObj.width;
		// var imgHeight = imgWidth / window.oldImgObj.width * window.oldImgObj.height;
		// if (imgHeight > height) {
		// imgWidth = height / window.oldImgObj.height * window.oldImgObj.width;
		// }
		moozImg(imgWidth);
	});
}

function moozImg(width) {
	var height = 0, bi = 1.00;
	if (width < window.cutWidth) {
		width = window.cutWidth;
	}
	bi = width / window.oldImgObj.width;
	height = window.oldImgObj.height * bi;
	if (height < window.cutHeight) {
		height = window.cutHeight;
		bi = height / window.oldImgObj.height;
		width = window.oldImgObj.width * bi;
	}
	window.oldImgObj.bi = bi;
	$('#zoomText').text((parseInt(bi * 100)) + '%');
	$('#imgCon').css({ width : width, height : height });
	$('#imgConCutImg').css({ width : width, height : height });

	var conWidth = $('#showImgCon').innerWidth(), conHeight = $('#showImgCon').innerHeight();
	var imgLeft = (conWidth - width) / 2, imgTop = (conHeight - height) / 2;
	var cutLeft = (conWidth - window.cutWidth) / 2, cutTop = (conHeight - window.cutHeight) / 2;
	$('#imgCon').css({ left : imgLeft, top : imgTop });
	$('#imgConCut').css({ left : cutLeft, top : cutTop });
	$('#imgConCutImg').css({ left : imgLeft - cutLeft, top : imgTop - cutTop });
}
function loadImg(url, callback) {
	var img = new Image();
	img.src = url;
	if (img.complete) {
		if (callback)
			callback(img);
		return;
	}
	img.onload = function() {
		if (callback)
			callback(img);
	};
}

/* 支持原生的使用原生的 */
Function.prototype.bind = Function.prototype.bind || function(target) {
	if (1 < arguments.length) {
		var args = Array.prototype.slice.call(arguments, 1);
		args.unshift(this, target);
		return proxy.apply(null, args);
	}
	return proxy(this, target);
};
